﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.ServiceProcess;
using System.Diagnostics;

namespace FighterClubZero
{
    public partial class Form1 : Form
    {
        public NetworkInterface vpnAdapterInstance;
        public const string SERVICE_NAME = "SEVPNCLIENT";
        VpnCmdClient client = new VpnCmdClient();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //VpnCmdClient vpn = new VpnCmdClient("10000");
            //Response resp = vpn.VersionGet();
            //button1.Text = resp.Info;
            vpnAdapterInstance = getVPNAdapter();
            if (null == vpnAdapterInstance)
            {
                richTextBox1.Clear();
                richTextBox1.AppendText("获取虚拟网卡失败，请尝试在修复模式下使用平台\n");
            }
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            showConnectionStatus();
            richTextBox1.AppendText("初始化成功");
            richTextBox1.AppendText("\n");
            richTextBox1.AppendText("此版本为备胎平台FighterClubZero测试版本");
            richTextBox1.AppendText("\n");
            richTextBox1.AppendText("安装文件所包含的测试账号将在测试阶段结束后失效");
            if (checkDhcp())
            {
                dhcp.Text = "正常";
            }
            else {
                dhcp.Text = "异常";
                ServiceController dhcpService = SEUtils.getDhcpService();
                if (null != dhcpService)
                {
                    dhcpService.Start();
                }
                else {
                    SEUtils.startBat(".\\bat\\startDHCP.bat");
                }
                richTextBox1.AppendText("\n尝试启动本机DHCP服务");
            }
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }



        public NetworkInterface getVPNAdapter()
        {
            NetworkInterface vpnAdatper = null;
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();//获取本地计算机上网络接口的对象
            foreach (NetworkInterface adapter in adapters)
            {
                // 格式化显示MAC地址                
                PhysicalAddress pa = adapter.GetPhysicalAddress();//获取适配器的媒体访问（MAC）地址
                byte[] bytes = pa.GetAddressBytes();//返回当前实例的地址
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    sb.Append(bytes[i].ToString("X2"));//以十六进制格式化
                    if (i != bytes.Length - 1)
                    {
                        sb.Append("-");
                    }
                }
                if (adapter.Description.Contains("VPN Client Adapter") && adapter.Name.Contains("VPN Client") && adapter.NetworkInterfaceType.ToString().Equals("Ethernet"))
                {
                    vpnAdatper = adapter;
                    break;
                }
            }
            return vpnAdatper;
        }
        public NetworkInterface getVPNAdapterByID(string id)
        {
            NetworkInterface vpnAdatper = null;
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();//获取本地计算机上网络接口的对象
            foreach (NetworkInterface adapter in adapters)
            {
                // 格式化显示MAC地址                
                PhysicalAddress pa = adapter.GetPhysicalAddress();//获取适配器的媒体访问（MAC）地址
                byte[] bytes = pa.GetAddressBytes();//返回当前实例的地址
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    sb.Append(bytes[i].ToString("X2"));//以十六进制格式化
                    if (i != bytes.Length - 1)
                    {
                        sb.Append("-");
                    }
                }
                if (adapter.Id.Equals(id))
                {
                    vpnAdatper = adapter;
                    break;
                }
            }
            return vpnAdatper;
        }

        public bool checkSoftEtherIsInstalled()
        {
            bool flag = false;
            ServiceController ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == "SEVPNCLIENT");
            if (ctl == null)
                flag = false;
            else
                flag = true;
            return flag;
        }



        private void timer1_Tick(object sender, EventArgs e)
        {
            if (null == vpnAdapterInstance)
            {
                connection_status.Text = "未知";
            }
            else {
                NetworkInterface adapter = getVPNAdapterByID(vpnAdapterInstance.Id);
                IPInterfaceProperties ip = adapter.GetIPProperties();
                //获取单播地址集
                UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
                foreach (UnicastIPAddressInformation ipadd in ipCollection)
                {
                    //InterNetwork    IPV4地址      InterNetworkV6        IPV6地址
                    //Max            MAX 位址
                    if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
                        //判断是否为ipv4
                        ipAddress.Text = ipadd.Address.ToString();//获取ip
                }
                if (adapter.OperationalStatus == OperationalStatus.Up)
                {
                    connection_status.Text = "已连接";
                }
                else
                {
                    connection_status.Text = "连接失败";
                }
            }
        }

        public void showConnectionStatus()
        {
            NetworkInterface adapter = getVPNAdapterByID(vpnAdapterInstance.Id);
            IPInterfaceProperties ip = adapter.GetIPProperties();
            //获取单播地址集
            UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
            foreach (UnicastIPAddressInformation ipadd in ipCollection)
            {
                //InterNetwork    IPV4地址      InterNetworkV6        IPV6地址
                //Max            MAX 位址
                if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
                    //判断是否为ipv4
                    ipAddress.Text = ipadd.Address.ToString();//获取ip
            }
            if (adapter.OperationalStatus == OperationalStatus.Up)
            {
                connection_status.Text = "已连接";
            }
            else
            {
                connection_status.Text = "连接失败";
            }
            
        }

        public bool checkDhcp()
        {
            bool flag = false;
            ServiceController ctl = SEUtils.getDhcpService();
            if (ctl.Status == ServiceControllerStatus.Running)
            {
                flag = true;
            }
            return flag;
        }


        private void button4_Click(object sender, EventArgs e)
        {
            Clipboard.SetDataObject(ipAddress.Text + ":46318");
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                //string targetDir = string.Format(@"D:\adapters\setup");//this is where mybatch.bat lies
                //proc = new Process();
                ////proc.StartInfo.WorkingDirectory = targetDir;
                //proc.StartInfo.FileName = ".\\disConnect.bat";
                //proc.StartInfo.Arguments = string.Format("10");//this is argument
                //proc.StartInfo.CreateNoWindow = true;
                //proc.Start();
                //proc.WaitForExit();
                client.AccountDisconnect("test");
            }
            catch (Exception ex)
            {
                //Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
            }
            finally
            {
                Application.Exit();
            }

        }

        private void reConnect_Click(object sender, EventArgs e)
        {
            try
            {
                //string targetDir = string.Format(@"D:\adapters\setup");//this is where mybatch.bat lies
                //proc = new Process();
                ////proc.StartInfo.WorkingDirectory = targetDir;
                //proc.StartInfo.FileName = ".\\accountConnect.bat";
                //proc.StartInfo.Arguments = string.Format("10");//this is argument
                //proc.StartInfo.UseShellExecute = false;
                //proc.StartInfo.RedirectStandardOutput = true;
                //proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                //proc.StartInfo.CreateNoWindow = true;
                //proc.Start();
                //proc.WaitForExit();
                Response resp = client.AccountConnect("test");
                if (resp.Success)
                {
                    richTextBox1.AppendText("\n手动连接 成功");
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
                richTextBox1.AppendText(ex.Message);
                richTextBox1.AppendText(ex.StackTrace.ToString());
            }
        }

    }
}
